import paramiko


class ConnectSystem:
    def __init__(self, ip, port, user, password):
        self.ip = ip
        self.port = port
        self.user = user
        self.password = password
        self.ssh = None
        self.sftp = None
        self.tran = None

    def ssh_connect(self):
        # 创建SSHClient 实例对象
        self.ssh = paramiko.SSHClient()
        # 调用方法，表示没有存储远程机器的公钥，允许访问
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 连接远程机器，地址，端口，用户名密码
        self.ssh.connect(self.ip, self.port, self.user, self.password, timeout=10)
        return self.ssh

    def sftp_connect(self):
        # 获取Transport实例
        self.tran = paramiko.Transport((self.ip, self.port))
        # 连接SSH服务端，使用password
        self.tran.connect(username=self.user, password=self.password)
        # 获取SFTP实例
        self.sftp = paramiko.SFTPClient.from_transport(self.tran)
        return self.sftp

    def exec(self, command, timeout=10, encoding='utf-8'):
        stdin, stdout, stderr = self.ssh.exec_command(command, timeout=timeout)
        ## bytes 转 str
        r_stdout = str(stdout.read(), encoding=encoding)
        r_stderr = str(stderr.read(), encoding=encoding)
        print(r_stdout)
        # print(r_stderr)
        return r_stdout, r_stderr

    def put_file(self, local_path, remote_path):
        """
        上传文件到远程服务器
        上传的本地/远程文件路径
        :param local_path: "D:/data/0603/test.txt"
        :param remote_path: "/opt/file/test.txt"
        """

        if not self.tran:
            self.sftp_connect()
        # 执行上传动作
        self.sftp.put(local_path, remote_path)
        # 关闭连接
        self.tran.close()

    def get_file(self, local_path, remote_path):
        """
        下载远程服务器文件
        远程文件路径/下载的本地
        :param local_path: "D:/data/0603/test.txt"
        :param remote_path: "/opt/file/test.txt"
        """

        if not self.tran:
            self.sftp_connect()
        # 执行上传动作
        self.sftp.get(remote_path, local_path)
        # 关闭连接
        self.tran.close()

    def disconnect(self):
        if self.ssh is not None:
            self.ssh.close()
        if self.sftp is not None:
            self.sftp.close()
        if self.tran is not None:
            self.tran.close()



if __name__ == '__main__':
    _ip = "192.168.80.128"
    _port = 22
    _user = "root"
    _password = "123456"

    _system = ConnectSystem(_ip, _port, _user, _password)
    _system.ssh_connect()
    _out, _err = _system.exec('cd /opt/ ;ls')
    _system.disconnect()

